package com.dsj.app.service.impl;

import com.dsj.app.service.DrugService;
import com.dsj.app.mapper.DrugMapper;
import com.dsj.app.mapper.SupplierMapper;
import com.dsj.app.domain.Drug;
import com.dsj.app.domain.DrugDO;
import com.dsj.app.domain.Supplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 药品管理业务实现
 */
@Service
public class DrugServiceImpl implements DrugService {

  @Autowired
  private DrugMapper drugMapper;

  @Autowired
  private SupplierMapper supplierMapper;

  @Override
  public Drug selectDrugByPrimaryKey(String id) {
    return drugMapper.selectByPrimaryKey(id);
  }

  @Override
  public List<DrugDO> selectAllDrug(Map<String, Object> params) {
    return drugMapper.selectAllDrug(params);
  }

  @Override
  public int count() {
    return drugMapper.count();
  }

  @Override
  public int insertDrug(Drug drug) {
    Drug find = drugMapper.selectByPrimaryKey(drug.getId());
    if (null != find) {
      throw new IllegalArgumentException("药品编号已经存在");
    }
    Optional<Supplier> supplier = Optional.ofNullable(supplierMapper.
            selectByPrimaryKey(drug.getSupplierId()));
    supplier.orElseThrow(() -> new IllegalArgumentException("供应商编号不存在"));
    return drugMapper.insertSelective(drug);
  }

  @Override
  public int updateDrug(Drug drug) {
    return drugMapper.updateByPrimaryKeySelective(drug);
  }

  @Override
  public int deleteDrug(String id) {
    return drugMapper.deleteByPrimaryKey(id);
  }
}
